<template>
	<view>
		<u-popup mode="center" v-model="show" :mask-close-able="false" :safe-area-inset-bottom="true" border-radius="20" width="500rpx" z-index="1000">
			<view class="check-version-content">
				<view class="pop-title">
					<text style="font-size: 32rpx;">发现新版本</text>
				</view>
				<view class="capy-text">
					v{{versionName+'('+updateVersion+')'}}
				</view>
				<scroll-view scroll-y="true" style="max-height: 300rpx;margin: 30rpx 0 60rpx;">
					<view class="">
						更新内容：
					</view>
					<view v-if="versionLog.length!==0">
						<view v-for="(item,index) in versionLog" :key="index" style="margin:10rpx 0 0 10rpx ; "> 
							{{index+1}}.{{item}}
						</view>
					</view>
					<view  v-else style="margin:10rpx 0 0 10rpx ; ">
						1.修复一些BUG
					</view>
				</scroll-view>
				<view style="margin-bottom: 30rpx;
				text-align: left;" v-if="!forceUpgrade">
					<u-checkbox v-model="noCheck" :disabled="false" :size="30" :label-size="26" active-color="#FFBB1A" >忽略此版本</u-checkbox>
				</view>
				<view class="confrim-btn">
					<u-button @click="downloadNewVersion()" class="update-btn">立即更新</u-button>
					<view class="next-say" v-if="!forceUpgrade" @click="nextUpdate()">
						下次再说
					</view>
				</view>
			</view>
		</u-popup>
		
		<u-popup mode="center" v-model="downShow" :mask-close-able="false" :safe-area-inset-bottom="true" border-radius="20" width="600rpx" z-index="1002">
			<view class="check-version-content">
				<view class="pop-title">
					<text style="font-size: 32rpx;">下载新版本</text>
				</view>
				<view class="progress-content">
					<u-line-progress active-color="#2979ff" :striped="true" :striped-active="true" :percent="progress"></u-line-progress>
				</view>
				<view style="text-align: center;">
					<text v-if="!completeDown" >正在下载资源：{{totalBytesWritten+'/'+totalBytesExpectedToWrite}}</text>
					<text v-if="completeDown" >正在更新，请稍后。。。</text>
				</view>
			
				<view class="confrim-btn" v-if="!completeDown">
					<view class="next-say" @click="cancelShow = true" style="color: #FF0000;">
						取消下载
					</view>
				</view>
			</view>
		</u-popup>
		<!-- v-model="$store.state.user.checkStatus==1" -->
		<!-- v-model="$store.state.user.checkStatus == 1" -->
		<u-popup mode="center" v-model="checkStatusOne"
			:mask-close-able="false" :safe-area-inset-bottom="true" 
			class="check-realname"
			 width="600rpx" z-index="1002">
				<view class="check-realname-content">
					<image src="/static/home/checkNoReal.png" mode="widthFix" style="width: 100%;"></image>
					<view class="u-font-32 u-m-t-34 u-m-b-50 u-text-center" style="font-weight: 500;">您还未实名认证~</view>
					<view class="u-flex u-row-center">
						<view class="real-btn" @click="$mRouter.push({route:'/pages/wo/shezhi/shiming'})" >
							立即认证
						</view> 
					</view>  
				</view>
			<view class="empty-close" @click="closeCheckStatus"></view>
		</u-popup>
		
		<u-popup mode="center"	v-model="checkStatusTwo"
			:mask-close-able="false" :safe-area-inset-bottom="true" 
			class="check-realname"
			 width="600rpx" z-index="1002">
				<view class="check-realname-content">
					<image src="/static/home/checkNoShop.png" mode="widthFix" style="width: 100%;"></image>
					<view class="u-font-32 u-m-t-34 u-m-b-50 u-text-center" style="font-weight: 500;">您还未与企业关联~</view>
					<view class="u-flex u-row-center">
						<view class="real-btn" @click="$mRouter.push({ route: '/pages/wo/createShop/index?type=add' })" >
							立即注册
						</view>
						<view class="real-btn u-m-l-20"  @click="$mRouter.push({ route: '/pages/wo/userCode' })" >
							加入企业
						</view>
					</view>  
				</view>
			<view class="empty-close" @click="closeCheckStatus"></view>
		</u-popup>
		<u-modal v-model="cancelShow" :title-style="{color: 'red'}" @confirm="cancelDown()" @cancel="cancelShow = false">
			<view class="slot-content">
				<text>您确定要取消下载吗？</text>
			</view>
		</u-modal>
	</view>
</template>

<script>
	export default {
		name:"check-update",
		data() {
			return {
				showT:true,
				show:false,
				downShow:false,
				noCheck:false,
				forceUpgrade:false,
				versionName:null,
				versionId:null,
				versionUrl:null,
				versionLog:[],
				progress:0,
				totalBytesWritten:0,
				totalBytesExpectedToWrite:0,
				cancelShow:false,
				downloadTask:null,
				completeDown:false,
				isWgt:false,
				updateVersion:'',
				timer:null,
			};
		},
		async mounted(){
			let that = this;
			clearTimeout(this.timer)
			this.timer = setTimeout(()=>{
				that.checkVersion();
			},500)
		},
		computed:{
			checkStatusOne(){
				return this.$store.state.user.checkStatus == 1;
			},
			checkStatusTwo(){
				return this.$store.state.user.checkStatus == 2;
			},
			checkStatusThree(){
				return this.$store.state.user.checkStatus == 3;
			},
			checkStatusFour(){
				return this.$store.state.user.checkStatus == 4;
			},
		},
		props:{
			dadType:''
		},
		methods:{ 
			closeCheckStatus(){
				this.$store.commit('user/SET_CHECK_STATUS',3);
			},
			// 格式化版本号
			division(arg1, arg2) {
				let t1, t2, r1, r2;
				try{
					t1 = arg1.toString().split('.')[1].length;
				} catch(e) {
					t1 = 0;
				}
				try{
					t2 = arg2.toString().split('.')[1].length;
				} catch(e) {
					t2 = 0;
				}
				r1 = Number(arg1.toString().replace('.', ''));
				r2 = Number(arg2.toString().replace('.', ''));
				return (r1/r2) * Math.pow(10, t2 - t1);
			},
			// 检测是否有新版本要更新
			async checkVersion(){
				// #ifdef APP-PLUS
				let device = uni.getSystemInfoSync().platform;
				let params = {
					appPlatform:device === 'ios'?1:2
				}	
				const res =await this.$http.get('api/AppPackage/GetAppPackage',{params:params});
				try{
					if(res){
						let that = this;
						let versionText = this.dadType;
						plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
							let version = parseInt(widgetInfo.versionCode);//当前版本
							that.updateVersion = parseInt(res.code);//数据库最新版本
							if(that.updateVersion>version){ 
								if(versionText == 'isVersion'){ 
									uni.hideLoading({
										title: '检查更新',
										mask: false
									})
								}
								that.forceUpgrade = res.forceUpgrade;
								that.versionName = res.name;
								that.versionId = res.resourceId;
								that.versionUrl = res.url;
								that.isWgt = res.isWgt;
								that.versionLog = JSON.parse(res.upgradeLog);
								// 判断是不是已经给忽略此版本了
								if(!uni.getStorageSync(that.versionName+that.updateVersion)){
										that.show = true;
								}else{  
									if(that.$store.state.user.checkStatus == 0&&that.$store.state.user.user.id){
										if(!that.$store.getters['user/isAuthRealName']){
											if(!that.$store.getters['user/isApprovalIng']){
												that.$store.commit('user/SET_CHECK_STATUS',1);
											}else{
												that.$store.commit('user/SET_CHECK_STATUS',3);
											}
										}else if( that.$store.state.shop.shopList.length===0){
											that.$store.commit('user/SET_CHECK_STATUS',2);
										}else{
											that.$store.commit('user/SET_CHECK_STATUS',3);
										}
									}
								}
							}else{
								if(versionText == 'isVersion'){
									uni.showToast({
										title: '已是最新版本'
									});	
								}else{  
									if(that.$store.state.user.checkStatus == 0&&that.$store.state.user.user.id){
										if(!that.$store.getters['user/isAuthRealName']){
											if(!that.$store.getters['user/isApprovalIng']){
												that.$store.commit('user/SET_CHECK_STATUS',1);
											}else{
												that.$store.commit('user/SET_CHECK_STATUS',3);
											}
										}else if( that.$store.state.shop.shopList.length===0){
											that.$store.commit('user/SET_CHECK_STATUS',2);
										}else{
											that.$store.commit('user/SET_CHECK_STATUS',3);
										}
									}
								}
								
							}
						})
						
					}else{
						
					}
				}catch(e){
					let that = this;
					if(that.$store.state.user.checkStatus == 0&&that.$store.state.user.user.id){
						if(!that.$store.getters['user/isAuthRealName']){
							if(!that.$store.getters['user/isApprovalIng']){
								that.$store.commit('user/SET_CHECK_STATUS',1);
							}else{
								that.$store.commit('user/SET_CHECK_STATUS',3);
							}
						}else if( that.$store.state.shop.shopList.length===0){
							that.$store.commit('user/SET_CHECK_STATUS',2);
						}else{
							that.$store.commit('user/SET_CHECK_STATUS',3);
						}
					}
					//TODO handle the exception
					this.$u.toast('程序异常，错误信息：'+e)
				}
				// #endif
				// #ifdef H5
				console.log('触发弹窗校验');
				if(this.$store.state.user.checkStatus == 0&&this.$store.state.user.user.id){
					if(!this.$store.getters['user/isAuthRealName']){
						if(!this.$store.getters['user/isApprovalIng']){
							this.$store.commit('user/SET_CHECK_STATUS',1);
						}else{
							this.$store.commit('user/SET_CHECK_STATUS',3);
						}
					}else if( this.$store.state.shop.shopList.length===0){
						this.$store.commit('user/SET_CHECK_STATUS',2);
					}else{
						this.$store.commit('user/SET_CHECK_STATUS',3);
					}
				}
				// #endif
				
			},
			// 下载新版本文件
			async downloadNewVersion(){
				let device = uni.getSystemInfoSync().platform;
				if(device === 'ios'&&!this.isWgt){
					let appUrl = 'itms-apps://itunes.apple.com/cn/app/id1621645290';// XXXX为对应的AppID
					plus.runtime.openURL(appUrl);
					return false;
				}
				this.downShow = true;
				let that = this;
				this.completeDown = false;
				this.downloadTask = uni.downloadFile({
					// url: that.resourcesUrl+that.versionId, //仅为示例，并非真实的资源
					url: that.versionUrl, //仅为示例，并非真实的资源
					success: (res) => {
						if (res.statusCode === 200) {
							that.completeDown = true;
							that.installAPKorWGT(res.tempFilePath);
						}
					}
				});
				this.downloadTask.onProgressUpdate((res) => {
					this.progress = res.progress;
					this.totalBytesWritten = this.division(res.totalBytesWritten,1048576).toFixed(2)+'MB';
					this.totalBytesExpectedToWrite =this.division(res.totalBytesExpectedToWrite,1048576).toFixed(2)+'MB';
					// 满足测试条件，取消下载任务。
					// if (res.progress > 50) {
					// 	downloadTask.abort();
					// }
				});
			},
			// 点击下次再说
			nextUpdate(){
				if(this.noCheck){
					uni.setStorageSync(this.versionName+this.updateVersion,true)
				}
				this.show = false; 
			},
			// 取消下载
			cancelDown(){
				this.downloadTask.abort(); 
				this.progress = 0;
				this.totalBytesWritten = 0;
				this.cancelShow = false;
				this.downShow = false;
			},
			installAPKorWGT(path){
				let that = this;
				plus.runtime.install(path, {}, function() {
					plus.nativeUI.alert("应用资源更新完成,请重新启动！", function() {
						plus.runtime.restart();
					});
				}, function(e) {
					that.downShow = false;
					plus.nativeUI.alert("安装更新文件失败[" + e.code + "]：" + e.message);
					// if (e.code == 10) {
					// 	alert('请清除临时目录');
					// }
				});
			}
		
		}
	}
</script>

<style lang="scss" scoped>
 .check-version-content{
	 box-sizing: border-box;
	 padding: 40rpx;
	 
	 .pop-title{
		 font-size: 32rpx !important;
		 font-weight: bold;
		 text-align: center;
	 }
	 .capy-text{
		 font-size: 28rpx;
		 color: #d1d1d1;		 
		 text-align: center;
	 }
	 .progress-content{
		 margin: 30rpx 0;
	 }
	 .update-btn{
		 background-color: #FFBB1A;
		 border: none;
		 
	 }
	 .next-say{
		 text-align: center;
		 margin-top: 20rpx;
	 }
	
 }
 .check-realname{
 	::v-deep .u-mode-center-box{
 		background-color: transparent !important;
 	}
	.check-realname-content{
		background-color: #fff;
		border-radius: 20rpx;
		box-sizing: border-box;
		padding: 38rpx 48rpx 48rpx;
		.real-btn{
			box-sizing: border-box;
			padding: 28rpx 60rpx;
			background-color: #FFBB1A;
			box-shadow: 0px 8rpx 15rpx 3rpx rgba(255,187,26,0.24);
			border-radius: 45rpx;
		}
	}
 	.empty-close{
 		background: url('/static/order/closebg.png') no-repeat;
 		background-size: 100% 100%;
 		width: 62rpx;
 		height: 62rpx;
 		margin: 60rpx auto 0;
 	}
 	
 }
 .slot-content{
 		 box-sizing: border-box;
 		 padding: 30rpx 60rpx;
 }
</style>
